#include <buola/image/format.h>
#include <buola/image/io.h>
#include <buola/image/algorithm/calibration.h>
#include <buola/app/ccmdline.h>
#include <buola/io/cfolder.h>
#include <buola/image/cimagegc.h>

using namespace buola;

int main(int pNArg,char **pArgs)
{
    buola_init(pNArg,pArgs);

    try
    {
        if(cmd_line().ArgCount()<2)
        {
            msg_info() << "must specify source and destination folder\n";
            return -1;
        }
        io::CURI lURI=io::uri(cmd_line().Arg(0));
        io::CURI lDestURI=io::uri(cmd_line().Arg(1));
        io::CFolder lFolder(lURI);

        std::vector<io::CURI> lFiles=lFolder.GetChildrenURIs();

        int lCount=0;
        
        for(const auto &u : lFiles)
        {
            if(u.Extension()!="pcd") continue;
            auto lImage=img::load<img::CImage_rgb8>(u);
            std::vector<CPoint_d> lCorners;
            bool lFound=img::find_chessboard_corners(lImage,6,5,lCorners,0);
            if(lFound)
            {
                save(lImage,lDestURI/("calibration"+to_string(lCount)+".ppm"));
                
                img::CImageGC<img::TFormat_rgb8> lGC(lImage);
                lGC.SetSource(img::CColor(0.3,1.0,0.2));
                for(const auto &p : lCorners)
                {
                    lGC.Path().Arc(p,5);
                    lGC.FillPath();
                }
                save(lImage,io::file("calibration"+to_string(lCount)+".png"));
                msg_info() << u.Name() << "   " << ++lCount << "\n";
            }
        }
    }
    catch(std::exception &pE)
    {
        msg_info() << "caught exception " << pE.what() << "\n";
    }

    return buola_finish();
}
